package com.bnq.logc.utils

import android.content.Context
import android.content.DialogInterface
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import com.bnq.logc.R
import com.google.android.material.dialog.MaterialAlertDialogBuilder

class AlertDialogUtil {

    companion object{

        fun showEditDialog(context: Context,title:String,hint:String,content:String,
                           cancelText:String = "取消",cancel:(DialogInterface)->Unit = {},
                           confirmText:String = "确定",confirm:(DialogInterface,String)->Unit = {dialog, content->}){
            val dialog = MaterialAlertDialogBuilder(context)
                .setTitle(title)
                .setView(R.layout.dialog_edit_logc)
                .setNegativeButton(cancelText,
                    DialogInterface.OnClickListener { dialog, which -> cancel(dialog!!) })
                .setPositiveButton(confirmText,
                    DialogInterface.OnClickListener { dialog, which ->
                        val editText = (dialog as AlertDialog).findViewById<EditText>(R.id.editText)
                        confirm(dialog,editText?.text?.toString()?:"")
                    })
                .show()
            dialog.findViewById<EditText>(R.id.editText)?.apply {
                setHint(hint)
                setText(content)
            }
        }

        fun showCommonDialog(context: Context,title:String,content:String,
                             cancelText:String = "取消",cancel:(DialogInterface)->Unit = {},
                             confirmText:String = "确定",confirm:(DialogInterface)->Unit = {}){
            MaterialAlertDialogBuilder(context)
                .setMessage(content)
                .setTitle(title)
                .setNegativeButton(cancelText,
                    DialogInterface.OnClickListener { dialog, which -> cancel(dialog!!) })
                .setPositiveButton(confirmText,
                    DialogInterface.OnClickListener { dialog, which -> confirm(dialog!!) })
                .show()
        }

        fun showCommonListDialog(context: Context, items:Array<CommonItem>){
            MaterialAlertDialogBuilder(context)
                .setItems(items) { dialog, what ->
                    items[what].callback(dialog,items[what])
                }.show()
        }

        data class CommonItem(val key:Int,val text:String,val tag:Any? = null,val callback:(DialogInterface,CommonItem)->Unit):CharSequence {

            override val length: Int
                get() = text.length

            override fun get(index: Int): Char = text[index]

            override fun subSequence(startIndex: Int, endIndex: Int): CharSequence =
                text.subSequence(startIndex,endIndex)

            override fun toString(): String = text
        }
    }
}